﻿using System;
using System.ComponentModel.Composition.Hosting;
using System.ComponentModel.Composition.Primitives;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Web;
using System.Web.Mvc;

namespace Mefisto4.Core.MEF
{
    public class MEFHttpApplication : HttpApplication
    {
        public static ComposablePartCatalog RootCatalog { get; private set; }
        public static CompositionContainer ApplicationContainer { get; private set; }
        public static ComposablePartCatalog ControllerCatalog { get; private set; }

        protected virtual void Application_Start()
        {
            if (RootCatalog == null)
                RootCatalog = CreateRootCatalog();
            
            if (ApplicationContainer == null)
                ApplicationContainer = new CompositionContainer(RootCatalog, false);
            
            if (ControllerCatalog == null)
            {
                var controllerTypes = Assembly.GetExecutingAssembly().GetTypes().Where(t => t.GetInterfaces().Any(i => i == typeof(IController)));
                ControllerCatalog = new TypeCatalog(controllerTypes);
            }

            ControllerBuilder.Current.SetControllerFactory(new MEFControllerFactory());
        }

        protected virtual void Application_End()
        {
            if (ApplicationContainer != null)
                ApplicationContainer.Dispose();
        }

        protected virtual ComposablePartCatalog CreateRootCatalog()
        {
            return new DirectoryCatalog(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "bin"));
        }
    }
}